package interviewpreparationkit.dictionary

import java.util.ArrayList

/**
 * [Frequency Queries](https://www.hackerrank.com/challenges/frequency-queries)
 * 使用BufferedReader读取Input，否则容易超时
 */
// Complete the freqQuery function below.
fun freqQuery(queries: Array<Array<Int>>): ArrayList<Int> {
    val maxFreq = queries.size
    val ans = ArrayList<Int>(maxFreq / 2)
    val map = LinkedHashMap<Int, Int>(maxFreq / 2)
    var lastQuery = -1
    var lastResult = 0
    for (query in queries) {
        val key = query[1]
        when (query[0]) {
            1 -> {
                map[key] = map.getOrDefault(key, 0) + 1
                lastQuery = -1

            }
            2 -> {
                val v = map.getOrDefault(key, 0)
                if (v > 0) {
                    map[key] = v - 1

                }
                lastQuery = -1
            }
            3 -> {
                if (lastQuery != key) {
                    lastResult = if (key > maxFreq) {
                        0
                    } else {
                        if (map.values.contains(key)) 1 else 0
                    }
                    lastQuery = key
                }
                ans.add(lastResult)
            }
        }
    }

    return ans
}